package com.caiyigo.baihua.shiro;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.caiyigo.baihua.Const.Const;
import com.caiyigo.baihua.Const.UrlConfig;
import com.caiyigo.baihua.dao.SystemLogMapper;
import com.caiyigo.baihua.dao.SystemResMapper;
import com.caiyigo.baihua.model.SystemLog;
import com.caiyigo.baihua.model.SystemUser;
import com.caiyigo.baihua.utils.IpUtil;

/**
 * @author caihaihui
 * 
 */
@Repository
public class ShiroInterceptor extends HandlerInterceptorAdapter {

	private static SystemResMapper resMapper;

	@Resource(name = "systemLogMapper")
	SystemLogMapper logMapper;

	@Autowired
	public ShiroInterceptor(SystemResMapper resMapper) {
		ShiroInterceptor.resMapper = resMapper;
	}

	/**
	 * @return the resMapper
	 */
	public SystemResMapper getResMapper() {
		return resMapper;
	}

	/**
	 * @param resMapper
	 *            the resMapper to set
	 */
	public void setResMapper(SystemResMapper resMapper) {
		this.resMapper = resMapper;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		if (urls == null) {
			urls = resMapper.getUrls();
		}

		String url = request.getServletPath();

		if (urls.contains(url) && !ext.hasPermission(url)) {
			PrintWriter writer = null;

			response.setContentType("text/html;charset=UTF-8");
			writer = response.getWriter();
			writer.write(html401);
			writer.flush();
			if (writer != null)
				writer.close();

			return false;
		}
		SystemUser user = (SystemUser) ShiroExt
				.getSessionAttr(Const.SESSION_USER);
		if (!isContainsStaticResource(url)) {
			for (String string : UrlConfig.getLogFiledMap().keySet()) {
				if (url.indexOf(string) != -1) {
					logMapper.insertSelective(new SystemLog(
							(null == user ? 9999 : user.getId()), UrlConfig
									.getLogFiledMap().get(string), url, IpUtil
									.getIp(request), new Date(),
							getAllParams(request)));
				}
			}
		}

		if (null != user) {
			request.setAttribute("currentUserId",
					null == user ? "-1" : user.getId());
			request.setAttribute("username", user.getChinesename());
		}

		return super.preHandle(request, response, handler);
	}

	public static boolean isContainsStaticResource(String url) {
		for (String key : UrlConfig.getStaticResourceMap().keySet()) {
			if (url.contains(key)) {
				return true;
			}
		}
		return false;
	}

	public static String getAllParams(HttpServletRequest request) {
		StringBuffer buffer = new StringBuffer();
		String para = null;
		Enumeration<String> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			para = e.nextElement();
			buffer.append(para + ":"
					+ URLDecoder.decode(request.getParameter(para)) + ",");

		}
		return buffer.toString();
	}

	protected static final String html401 = "<html><head><title>401 Unauthorized</title></head><body bgcolor='white'><center><h1>401 Unauthorized</h1></center><hr><center></center></body></html>";
	private static ShiroExt ext = new ShiroExt();

	/**
	 * 获取全部 需要控制的权限
	 */
	private static List<String> urls;

	public static void updateUrls() {
		urls = resMapper.getUrls();
	}
}
